import 'package:chat/controller/friend_detail_controller.dart';
import 'package:chat/model/friend_model.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

final FriendDetailController controller = Get.find();

class FriendDetailScreen extends StatefulWidget {
  const FriendDetailScreen({super.key});

  @override
  _FriendDetailScreenState createState() => _FriendDetailScreenState();
}

class _FriendDetailScreenState extends State<FriendDetailScreen> with SingleTickerProviderStateMixin {
  late double _topPosition; // 初始位置
  late AnimationController _controller;
  late Animation<double> _animation;
  bool _isFixed = false; // 是否已固定
  double _bgScale = 1.0; // 新增：背景图片缩放比例

  @override
  void initState() {
    super.initState();
    _controller = AnimationController(duration: const Duration(milliseconds: 300), vsync: this);
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    final screenHeight = MediaQuery.of(context).size.height;
    _topPosition = screenHeight * 0.2;
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  void _onVerticalDragUpdate(DragUpdateDetails details) {
    setState(() {
      final screenHeight = MediaQuery.of(context).size.height;
      print(screenHeight);
      print(screenHeight * 0.2);
      print(screenHeight * 0.6);
      print(screenHeight * 0.8);
      // if (_isAtBottom) {
      // 吸底状态下：向上拖动
      if (details.delta.dy < 0) {
        _isFixed = false;
        _topPosition += details.delta.dy;
        _topPosition = _topPosition.clamp(screenHeight * 0.2, screenHeight * 0.8);
        print('_topPosition up: $_topPosition');
        // 背景图片缩小（随拖动距离线性变化）
        _bgScale = 1 + (1 * ((_topPosition - screenHeight * 0.2) / (screenHeight * 0.6)));
        _bgScale = _bgScale.clamp(1, 2);
        print('_bgScale: $_bgScale');
        print('details.delta.dy up:${details.delta.dy}');
        if (details.delta.dy < -1) {
          print('details.delta.dy up:${details.delta.dy}');
          _animateTo(screenHeight * (0.2));
          _bgScale = 1;
          _isFixed = true;
        }
      }
      // } else {
      // 正常状态下：向下拖动
      if (details.delta.dy > 0) {
        _isFixed = false;
        _topPosition += details.delta.dy;
        _topPosition = _topPosition.clamp(screenHeight * 0.2, screenHeight * 0.8);
        print('_topPosition down: $_topPosition');
        // 背景图片放大（随拖动距离线性变化）
        _bgScale = 1 + (1 * ((_topPosition - screenHeight * 0.2) / (screenHeight * 0.6)));
        _bgScale = _bgScale.clamp(1, 2);
        print('_bgScale: $_bgScale');
        print('details.delta.dy down:${details.delta.dy}');
        if (details.delta.dy > 1) {
          print('details.delta.dy down:${details.delta.dy}');
          _animateTo(screenHeight * (0.8));
          _bgScale = 2;
          _isFixed = true;
        }
      }
      // }
    });
  }

  void _onVerticalDragEnd(DragEndDetails details) {
    final screenHeight = MediaQuery.of(context).size.height;
    if (_isFixed) return; // 如果固定状态，则不执行动画
    if (_topPosition > screenHeight * 0.5) {
      _animateTo(screenHeight * 0.8);
      _bgScale = 2;
    } else {
      _animateTo(screenHeight * 0.2);
      _bgScale = 1;
    }
  }

  // void _onVerticalDragEnd(DragEndDetails details) {
  //   final screenHeight = MediaQuery.of(context).size.height;
  //   // 非吸底状态下：向下拖动
  //   if (_isAtBottom == false) {
  //     if (_topPosition > screenHeight * 0.3) {
  //       _animateTo(screenHeight * (1 - 0.2));
  //       _isAtBottom = true;
  //       _bgScale = 2;
  //       _bgScaleEnd = _bgScale;
  //       print('down$_bgScaleEnd');
  //     } else {
  //       _animateTo(screenHeight * 0.2);
  //     }
  //   }
  //   // 吸底状态下：向上拖动
  //   if (_isAtBottom == true) {
  //     if (_topPosition < screenHeight * 0.7) {
  //       _animateTo(screenHeight * 0.2);
  //       _isAtBottom = false;
  //       _bgScale = 1;
  //       _bgScaleEnd = _bgScale;
  //       print('up$_bgScaleEnd');
  //     } else {
  //       _animateTo(screenHeight * (0.8));
  //     }
  //   }
  // }

  void _animateTo(double target) {
    _animation = Tween<double>(begin: _topPosition, end: target).animate(_controller)..addListener(() {
      setState(() {
        _topPosition = _animation.value;
      });
    });
    _controller.reset();
    _controller.forward();
  }

  @override
  Widget build(BuildContext context) {
    final screenHeight = MediaQuery.of(context).size.height;
    final person = controller.personDetail.value!;
    return Scaffold(
      body: Stack(
        children: [
          // 全屏背景
          Container(
            color: Color(0XFFF2F3F7),
            child: Stack(
              children: [
                // 渐变消失的背景图（添加缩放效果）
                Positioned(
                  top: 80,
                  right: 40,
                  child: Transform.scale(scale: _bgScale, alignment: Alignment.topRight, child: Image.asset('assets/images/background.png', width: 150, height: 150, fit: BoxFit.contain)),
                ),
                // 自定义顶部导航栏
                Positioned(
                  top: MediaQuery.of(context).padding.top, // 考虑状态栏高度
                  left: 0,
                  right: 0,
                  child: Container(
                    height: kToolbarHeight, // 标准工具栏高度
                    padding: EdgeInsets.symmetric(horizontal: 16),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        // 返回按钮
                        IconButton(icon: Icon(Icons.arrow_back_ios, color: Colors.black), onPressed: () => Navigator.pop(context)),
                        // 设置按钮
                        IconButton(icon: Icon(Icons.settings, color: Colors.black), onPressed: () => Get.toNamed('/friendListScreen')),
                      ],
                    ),
                  ),
                ),
              ],
            ),
          ),
          // 可拖动面板（自适应高度+保持拖动）
          Positioned(
            top: _topPosition,
            left: 0,
            right: 0,
            child: GestureDetector(
              onVerticalDragUpdate: _onVerticalDragUpdate,
              onVerticalDragEnd: _onVerticalDragEnd,
              child: Container(
                height: screenHeight * 0.8,
                decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.vertical(top: Radius.circular(20))),
                child: Column(
                  children: [
                    // 内容区域
                    Container(
                      color: Color(0XFFF2F3F7),
                      child: Column(
                        children: [
                          Container(
                            padding: EdgeInsets.all(10),
                            decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.vertical(top: Radius.circular(20), bottom: Radius.zero)),
                            child: Column(children: [_buildUserInfoSection(person), SizedBox(height: 10), _buildTab(person)]),
                          ),
                          SizedBox(height: 10),
                          Container(decoration: BoxDecoration(color: Colors.white), child: Column(children: [_buildActionOptions(), _buildBottomButtons()])),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildUserInfoSection(Friend friendDetail) {
    return SizedBox(
      height: MediaQuery.of(context).size.height * 0.2 - 35,
      child: Row(
        children: [
          Stack(
            alignment: Alignment.bottomLeft,
            children: [
              CircleAvatar(radius: 50, backgroundImage: AssetImage(friendDetail.avatarUrl ?? "")),
              Positioned(
                right: 0,
                bottom: 0,
                child: Container(
                  width: 28,
                  height: 28,
                  decoration: BoxDecoration(color: Colors.white, shape: BoxShape.circle, boxShadow: [BoxShadow(color: Colors.black.withValues(alpha: 0.2), blurRadius: 4, offset: Offset(0, 2))]),
                  child: Icon(Icons.edit, size: 16, color: Colors.black),
                ),
              ),
            ],
          ),
          const SizedBox(width: 16),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(children: [Text(friendDetail.name, style: const TextStyle(fontSize: 24, fontWeight: FontWeight.bold)), Spacer(), Icon(Icons.arrow_forward_ios, color: Colors.black, size: 16)]),
                const SizedBox(height: 8),
                SizedBox(
                  child: Row(
                    children: [
                      SizedBox(width: 100, child: Text(friendDetail.ethAddress ?? "", style: TextStyle(fontSize: 14, color: Colors.grey[600]), overflow: TextOverflow.ellipsis)),
                      Icon(Icons.copy, color: Colors.grey[500], size: 16),
                    ],
                  ),
                ),
                const SizedBox(height: 8),
                Row(
                  mainAxisAlignment: MainAxisAlignment.start,
                  children: [
                    Container(
                      padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                      decoration: BoxDecoration(color: Color(0xFFE1F166), borderRadius: BorderRadius.circular(50)),
                      child: Text(friendDetail.ppcInfo ?? "", style: TextStyle(fontSize: 12, color: Colors.black)),
                    ),
                    const SizedBox(width: 10),
                    Container(
                      padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                      decoration: BoxDecoration(color: Color(0xFFE1F166), borderRadius: BorderRadius.circular(50)),
                      child: Text(friendDetail.hertInfo ?? "", style: TextStyle(fontSize: 12, color: Colors.black)),
                    ),
                  ],
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildTab(Friend friendDetail) {
    return SizedBox(
      height: 120,
      child: DefaultTabController(
        length: 2,
        child: Column(
          children: [
            TabBar(
              dividerHeight: 1,
              dividerColor: const Color(0xFFF5F6F7),
              indicatorColor: Colors.black, // 下划线颜色（选中状态）
              labelColor: Colors.black, // 选中标签颜色
              unselectedLabelColor: Colors.grey, // 未选中标签颜色
              labelStyle: const TextStyle(
                fontWeight: FontWeight.bold, // 选中标签加粗
              ),
              unselectedLabelStyle: const TextStyle(
                fontWeight: FontWeight.bold, // 未选中标签也加粗
              ),
              tabs: const [Tab(text: "财富信息"), Tab(text: "社交信息")],
            ),
            Expanded(child: TabBarView(children: [_buildWealth(friendDetail), _buildSocial(friendDetail)])),
          ],
        ),
      ),
    );
  }

  Widget _buildWealth(Friend person) {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 16),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          SizedBox(height: 10),
          Row(
            children: [const Text('RFG', style: TextStyle(fontSize: 12, fontWeight: FontWeight.bold)), Spacer(), const Text('456666666', style: TextStyle(fontSize: 12, fontWeight: FontWeight.bold))],
          ),
          SizedBox(height: 10),
          Row(
            children: [
              const Text('空闲NFT', style: TextStyle(fontSize: 12, fontWeight: FontWeight.bold)),
              Spacer(),
              Container(
                padding: EdgeInsets.all(2),
                decoration: BoxDecoration(border: Border.all(color: Color(0xFFF5F6F7), width: 1.5), borderRadius: BorderRadius.circular(50)),
                child: Row(
                  children: [
                    Container(
                      width: 20,
                      height: 20,
                      decoration: BoxDecoration(shape: BoxShape.circle, image: DecorationImage(image: AssetImage('assets/images/zh-CN-XiaochenNeural.png'), fit: BoxFit.cover)),
                    ),
                    const SizedBox(width: 8),
                    const Text('3a', style: TextStyle(fontSize: 12, fontWeight: FontWeight.bold)),
                  ],
                ),
              ),
              SizedBox(width: 10),
              Container(
                padding: EdgeInsets.all(2),
                decoration: BoxDecoration(border: Border.all(color: Color(0xFFF5F6F7), width: 1.5), borderRadius: BorderRadius.circular(50)),
                child: Row(
                  children: [
                    Container(
                      width: 20,
                      height: 20,
                      decoration: BoxDecoration(shape: BoxShape.circle, image: DecorationImage(image: AssetImage('assets/images/zh-CN-XiaochenNeural.png'), fit: BoxFit.cover)),
                    ),
                    const SizedBox(width: 8),
                    const Text('2y', style: TextStyle(fontSize: 12, fontWeight: FontWeight.bold)),
                  ],
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildSocial(Friend person) {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 16),
      child: Column(
        children: [
          SizedBox(height: 10),
          Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [const Text('Twitter', style: TextStyle(fontSize: 12, fontWeight: FontWeight.bold)), Spacer(), const Text('wechat', style: TextStyle(fontSize: 12, fontWeight: FontWeight.bold))],
          ),
        ],
      ),
    );
  }

  Widget _buildActionOptions() {
    return Column(children: [_buildActionItem('设置备注和描述', controller.setRemark), _buildActionItem('删除联系人', controller.deleteContact), _buildActionItem('加入黑名单', controller.addToBlacklist)]);
  }

  Widget _buildActionItem(String title, VoidCallback onTap) {
    return InkWell(
      onTap: onTap,
      child: Container(
        padding: EdgeInsets.symmetric(horizontal: 16, vertical: 12),
        child: Row(children: [Expanded(child: Text(title, style: TextStyle(fontSize: 16))), Icon(Icons.chevron_right, color: Colors.grey, size: 24)]),
      ),
    );
  }

  Widget _buildBottomButtons() {
    return Padding(
      padding: const EdgeInsets.all(16.0),
      child: Column(
        children: [
          InkWell(
            onTap: controller.startChat,
            child: Container(
              width: double.infinity,
              alignment: Alignment.center,
              padding: const EdgeInsets.symmetric(vertical: 10),
              decoration: BoxDecoration(color: Color(0XFFF2F3F7), borderRadius: BorderRadius.circular(20)),
              child: const Text('发起聊天', style: TextStyle(color: Color(0xFF377E8D), fontWeight: FontWeight.bold)),
            ),
          ),
          const SizedBox(height: 16),
          InkWell(
            onTap: controller.startChat,
            child: Container(
              width: double.infinity,
              alignment: Alignment.center,
              padding: const EdgeInsets.symmetric(vertical: 10),
              decoration: BoxDecoration(color: Color(0XFFF2F3F7), borderRadius: BorderRadius.circular(20)),
              child: const Text('语音通话', style: TextStyle(color: Color(0xFF377E8D), fontWeight: FontWeight.bold)),
            ),
          ),
        ],
      ),
    );
  }
}
